package com.example.demo2.service;

import com.example.demo2.bean.UserBean;
import com.example.demo2.dao.UserBeanDao;
import com.example.demo2.util.FileTool;
import com.example.demo2.util.PreReadUploadConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserBeanService {

    @Autowired
    UserBeanDao dao;

    public List<UserBean> list(){
        List<UserBean> all = dao.findAll();
        return all;
    }

    public UserBean login(UserBean yourBean) {
        UserBean yourBean1 = dao.findOne(Example.of(yourBean)).orElse(null);
        return yourBean1;
    }

    public UserBean register(UserBean yourBean) {
        UserBean save = dao.save(yourBean);
        return save;
    }

    public UserBean findone(UserBean yourBean) {
        UserBean yourBean1 = dao.findOne(Example.of(yourBean)).orElse(null);
        return yourBean1;
    }

    public void deleteById(Integer id) {
        dao.deleteById(id);
    }

    public UserBean update(UserBean yourBean) {
        UserBean save = dao.save(yourBean);
        return save;
    }

    public UserBean addone(UserBean yourBean) {
        UserBean save = dao.save(yourBean);
        return save;
    }

    public Map<String,Object> fileUpload(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        if (file.isEmpty()) {
            System.out.println("文件为空空");
            map.put("code", "1");
            map.put("msg","失败，文件为空");
            return map;
        }
        PreReadUploadConfig uploadConfig = null;
        String fileName = file.getOriginalFilename();
        fileName = FileTool.renameToUUID(fileName);
        try {
            FileTool.uploadFiles(file.getBytes(), uploadConfig.getUploadPath(), fileName);
        } catch (Exception e) {
        }
        if (fileName.isEmpty()) {
            map.put("code", "1");
            map.put("msg","失败，文件名有误");
            return map;
        }

        Map<String, Object> returnMap = new HashMap<>();
        String url = "/xmdata/" + fileName;

        returnMap.put("url", url);
        map.put("code", 0);
        map.put("msg", "成功");
        map.put("data", returnMap);
        return map;
    }

}
